'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
    errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
    config = require(path.resolve('./config/config')),
    jwt = require('jsonwebtoken'),
    mongoose = require('mongoose'),
    User = mongoose.model('User'),
    barcodeMasterController = require('../../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    BarcodeEnum = require('../../../../Barcode/server/controllers/Enum.server.controller');

/**
 * Signup
 */
exports.signup = function (req, res) {
    // For security measurement we remove the roles from the req.body object
    delete req.body.roles;

    // Init Variables
    var user = new User(req.body);

    // Then save the user
    user.save(function (err) {
        if (err) {
            return res.status(400).send({
                code: err.code,
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            login(user.usercode, user.password, false, function (err, obj) {
                if (err) {
                    return res.status(400).send(err);
                } else {
                    res.json(obj);
                }
            });
        }
    });
};

/**
 * Signin after passport authentication
 */
exports.signin = function (req, res, next) {
    login(req.body.usercode, req.body.password, function (err, obj) {
        if (err) {
            res.json({
                status: 'EEEE',
                desc: err.message
            });
        } else {
            res.json({
                status: '0000',
                data: obj
            });
        }
    });
};

exports.signinScan = function (req, res) {
    var barcode = req.body.Barcode;

    barcodeMasterController.findBarcodeMaster(barcode, function (err, record) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        if (record == null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '条码扫描失败';
            newErr.message = '该条码在系统中不存在！';
            res.json({
                Data: null,
                Error: newErr
            });
            return;
        }
        if (record.BarcodeType != BarcodeEnum.BarcodeType.Person) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询员工信息失败';
            newErr.message = '该条码不是员工条码！';
            res.json({
                Data: null,
                Error: newErr
            });
            return;
        }
        User.findOne({_id: record.EntityID}, function (err, user) {
            if (err) {
                res.json({
                    Data: null,
                    Error: err
                });
                return;
            }
            if (user == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查找用户失败';
                newErr.message = '该用户在系统中不存在！';
                res.json({
                    Data: null,
                    Error: newErr
                });
                return;
            }
            if (!user.IsEffective) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '无效的用户';
                newErr.message = '该用户已失效！';
                res.json({
                    Data: null,
                    Error: newErr
                });
                return;
            }
            var token = jwt.sign({
                _id: user._id,
                Code: user.Code,
                Roles: user.Roles
            }, config.jwtTokenSecret);
            res.json({
                Data: {
                    token: token
                },
                Error: null
            });
        });
    });
};

function login (usercode, password, callback) {
    var usercode = usercode || '';
    var password = password || '';

    if (usercode == '' || password == '') {
        callback({
            message: '用户名或密码不能为空'
        });
        return;
    }
    User.findOne({Code: usercode}, function (err, user) {
        if (err) {
            callback(err);
        } else {
            if (!user) {
                callback({
                    message: '该用户不存在'
                });
            } else if (!user.IsEffective) {
                callback({
                    message: '该用户已失效'
                });
            } else {
                user.authenticate(password, function(isMatch) {
                    if (!isMatch) {
                        callback({
                            message: '密码错误'
                        });
                    } else {
                        var token = jwt.sign({
                            _id: user._id,
                            Code: user.Code,
                            Roles: user.Roles
                        }, config.jwtTokenSecret);
                        callback(null, {
                            token: token
                        });
                    }
                });
            }
        }
    });
}
